package com.sicheng.metadata.juc.cas;

import java.util.concurrent.atomic.AtomicReference;

/**
 * @author : zsc
 * @date :
 * <p>
 * 自定义自旋锁
 */


public class SpanLock {
    private static final AtomicReference<Thread> atomic = new AtomicReference<>();

    public void lock() {
        Thread thread = Thread.currentThread();
        while (!atomic.compareAndSet(null, thread)) {
            System.out.println(thread.getName() + "请求锁");
        }
        System.out.println(thread.getName() + " lock ");
    }

    public void unlock() {
        Thread thread = Thread.currentThread();
        atomic.compareAndSet(thread, null);
        System.out.println(thread.getName() + " unlock ");
    }

    public static void main(String[] args) {


        try {
            SpanLock lock = new SpanLock();
            new Thread(() -> {
                try {
                    lock.lock();
                    Thread.sleep(2);
                    lock.unlock();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }, "aa").start();

            Thread.sleep(1);


            new Thread(() -> {
                lock.lock();
                lock.unlock();
            }, "bb").start();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
